import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'

//  meta含义
//  title   ------------------> 标题
//  hide    ------------------> 隐藏tabbar
//  keepAlive   ------------------> 是否缓存

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home',
    meta: { depth: 0 }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/Home.vue'),
    meta: { title: '首页', depth: 1 }
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('@/views/category/category.vue'),
    meta: { title: '分类', depth: 2 }
  },
  {
    path: '/heart',
    name: 'Heart',
    component: () => import('@/views/heart/heart.vue'),
    meta: { title: '收藏', depth: 3 }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/cart/cart.vue'),
    meta: { title: '购物车', keepAlive: true, depth: 4 }
  },

  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/profile/profile.vue'),
    meta: { title: '我的', depth: 5 }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/login.vue'),
    meta: { title: '登录', depth: 0 }
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => 1
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from) => {
  if (to.meta.depth > from.meta.depth) {
    useLoadStore().sync_update_slideName('slide-left')
  } else {
    useLoadStore().sync_update_slideName('slide-right')
  }
  const status = isStarted()
  if (status == false) start()
  return true
})

router.afterEach((to) => {
  const status = isStarted()
  if (status == true) done()
  document.title = to.meta.title ?? ''
})

export const initRouter = (app: App) => app.use(router)
export default initRouter
